<?php
namespace org\crawlgenie\application\environment;
use org\crawlgenie\application\base\Factory;
use org\crawlgenie\application\base\Application;
use org\crawlgenie\application\path\Path;

use \Logger;
use \CGException;


class RequestLogger {

    public static function logRequest(Application $application) {
        $db = Factory::getDBConn();

        $remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
        $clientIP = isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : null;
        $forwardedFor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;

        if(Request::isCommandLineInvocation()) {
            global $argv;
            $scriptName = $argv[0];
            $userIP = null;
        } else {
            $scriptName = basename($_SERVER['PHP_SELF']);
            if($forwardedFor == null) {
                if($clientIP == null) { 
                    $userIP = $_SERVER['REMOTE_ADDR'];                
                } else {
                    $userIP = $_SERVER['HTTP_CLIENT_IP'];
                }

            } else {
                $userIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
            }
        }
        
	$requestMethod = Request::isCommandLineInvocation() ? 'cli' : $_SERVER['REQUEST_METHOD'];
        $queryString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null;
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
        $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
        $cookies = (isset($_COOKIE) && count($_COOKIE) > 0) ? print_r($_COOKIE,true) : null;
        $module = Path::getCleanPath(Request::getParam('mod'));
        $service = Path::getCleanPath(Request::getParam('sv_name'));
        $renderTime = $application->getRenderTime();


        $storeQuery = "insert into "._CG_REQUEST_LOG_TABLE."
            (remote_addr,client_ip,x_forwarded_for,user_ip,user_agent," .
        " referrer,request_method,script_name,query_string,cookies," .
        " request_data,module,service,render_time,last_update)
            values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())";

        $storeValues = array($remoteAddr,$clientIP,$forwardedFor,$userIP,
            $userAgent, $referer, $requestMethod,
            $scriptName,$queryString,$cookies,
            Request::getAllParams(),$module,$service,$renderTime);
        
        $db->preparedQuery($storeQuery, $storeValues);

    }

}
?>
